//
//  BlogMainViewViewController.m
//  hospitalVIP
//
//  Created by Xiaoyan on 12-12-12.
//  Copyright (c) 2012年 MEETStudio. All rights reserved.
//

#import "BlogMainViewViewController.h"
#import "PersonalViewController.h"

static ASIHTTPConnection *getMicroBlogList_connect;



@interface BlogMainViewViewController (){
    
    int pageNo;
}

@end

@implementation BlogMainViewViewController
@synthesize myTableView;
@synthesize microBlogArray;

#pragma mark - 设置静态变量
//默认为TimelineRefTypeNone
static  KMicroBlogRefType  microBlogRefType = KMicroBlogRefTypeNone;

+ (void)setRefType:(KMicroBlogRefType)refType
{
    microBlogRefType = refType;
}



- (void)dealloc{
    
    [myTableView release];
    [microBlogArray release];
    
    if (getMicroBlogList_connect != nil) {
        getMicroBlogList_connect.connectionDelegate = nil;
        [getMicroBlogList_connect release];
        getMicroBlogList_connect = nil;
    }
    
    [super dealloc];
}



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.tabBarItem.image = [UIImage imageNamed:@"icon_friend.png"];
        self.tabBarItem.title = @"微博";
        self.title = @"微博";
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    
    
    pageNo = 1;
    //加载数据
//    [self.myTableView setContentOffset:CGPointMake(0,-66)];
//    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:self.myTableView];
//    
//    if (microBlogRefType == KMicroBlogRefTypeNew) {
//        [self headerRefData];
//        microBlogRefType = KMicroBlogRefTypeNone;
//    }

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setTItleWith:@"微博"];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"bg_pattern_wood" ofType:@"png"];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:path]];
    
    // Do any additional setup after loading the view from its nib.
    
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    
    if (microBlogArray == nil) {
        microBlogArray = [[NSMutableArray alloc]init];
    }
    
    pageNo = 1;
    
    
//    UIButton *rightBt = [[UIButton alloc]initWithFrame:CGRectMake(0, 7, 50, 30)];
//    [rightBt.titleLabel setFont:[UIFont systemFontOfSize:17]];
//    [rightBt.titleLabel setTextColor:[UIColor whiteColor]];
//    [rightBt setTitle:@"发布" forState:UIControlStateNormal];
//    [rightBt addTarget:self action:@selector(sendMicroBlog) forControlEvents:UIControlEventTouchUpInside];
//    
//    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:rightBt];
//    [self.navigationItem setRightBarButtonItem:rightButton];
//    [rightBt release];
//    [rightButton release];



    
    [self refreshView];
  
}

- (void)myMicroBlog{
    
    int userId = [[[NSUserDefaults standardUserDefaults] valueForKey:USER_ID] intValue];
    NSString *userName = [[NSUserDefaults standardUserDefaults] valueForKey:USER_NAME];
    
    PersonalViewController  *ViewController =   [[PersonalViewController alloc] initWithUserId:userId userName:userName];
    
    ViewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:ViewController animated:YES];
    [ViewController release];

    
}


- (void)sendMicroBlog{
    
    RecordViewController *ViewController =   [[RecordViewController alloc] init];
    
    ViewController.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:ViewController animated:YES];
    [ViewController release];

    
    
}


- (void)toUserView:(id)sender{
    
    UIButton *button = (UIButton *)sender;
    NSDictionary *dict = [microBlogArray objectAtIndex:button.tag];
    
    int userId = [[dict objectForKey:@"OwnerUserID"] intValue];
    NSString *userName = [dict objectForKey:@"Author"];
    
   
    
    PersonalViewController *con = [[PersonalViewController alloc]initWithUserId:userId userName:userName];
    con.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:con animated:YES];
    [con release];
    
    
}


- (void)loadData{
    
    NSString *userName = [[NSUserDefaults standardUserDefaults] valueForKey:USER_NAME];
    NSString *UserID = [[NSUserDefaults standardUserDefaults] valueForKey:USER_ID];
    
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileMicroBlog/%@/ListMicroBlogThreads.aspx?UserID=%@&pageNo=%d&pageSize=%d",BASEURL,userName,UserID,pageNo,20];
	NSURL *url = [NSURL URLWithString:urlString];
    
    if (getMicroBlogList_connect != nil) {
        
        [getMicroBlogList_connect release];
        getMicroBlogList_connect = nil;
    }
    
    getMicroBlogList_connect = [[ASIHTTPConnection alloc] initGETWithURL:url resultDict:YES isCache:YES];
    getMicroBlogList_connect.connectionDelegate = self;
    
    [getMicroBlogList_connect startAsynchronous];
    
}

#pragma mark connection delegate
- (void)requestFailed:(ASIHTTPConnection *)connection error:(NSError *)error URL:(NSURL *)url info:(NSDictionary *)info{
    
    [self bottomRefDone];
    [self headerRefDone];
        
}

- (void)requestFinished:(ASIHTTPConnection *)connection resultDict:(NSDictionary *)dict URL:(NSURL *)url info:(NSDictionary *)info{
    
        
    [LoadingView hideWithAnimated:YES];
    
    if (pageNo == 1) {
        [self headerRefDone];
    }
    else{
        [self bottomRefDone];
    }
    
    
    NSArray *array = [dict objectForKey:@"Records"];
    if (array.count > 0) {
        
        if (pageNo == 1) {
            [microBlogArray removeAllObjects];
           
        }
        
        [microBlogArray addObjectsFromArray:array];
        [self.myTableView reloadData];
        [self refreshView];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark tableView dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (microBlogArray.count == 0) {
        return 1;
    }
    
    return microBlogArray.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *MyIdentifier = @"TimelineUnitCell";
    
    // Try to retrieve from the table view a now-unused cell with the given identifier.
    TimelineUnitCell *cell =(TimelineUnitCell *) [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TimelineUnitCell"
                                                     owner:self options:nil];
#ifdef __IPHONE_2_1
        cell = (TimelineUnitCell *)[nib objectAtIndex:0];
#else
        cell = (TimelineUnitCell *)[nib objectAtIndex:1];
#endif
        
        cell.delegate = self;
        
        
    }
    
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
        NSDictionary *dict;
    if (microBlogArray.count > 0) {
        
        dict = [microBlogArray objectAtIndex:indexPath.row];
        [cell loadCellViewWith:dict ];
        [cell initNewsIconButton:dict];
        cell.iconButton.tag = indexPath.row;
        [cell.iconButton addTarget:self action:@selector(toUserView:) forControlEvents:UIControlEventTouchUpInside];
        

    }
                
         
    return cell;
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (microBlogArray.count == 0) {
        return;
    }
    
    NSDictionary *dict = [microBlogArray objectAtIndex:indexPath.row];
    TLDetailViewContentViewController * detailViewController =   [[TLDetailViewContentViewController alloc] initWithPost:dict];
    detailViewController.hidesBottomBarWhenPushed  =YES;
    
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
    
}




#pragma mark -
#pragma mark Table 下拉刷新
#pragma mark -
#pragma mark Data Source Loading / Reloading Methods


- (void)refreshView
{
    
    //顶部刷新条
    if ( _refreshHeaderView == nil) {
        
        _refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f- self.myTableView.bounds.size.height, 320, self.myTableView.bounds.size.height)];
        _refreshHeaderView.delegate = self;
         [self.myTableView addSubview:_refreshHeaderView];
    }
    
    
    //底部刷新条
    if ( _refreshTailView == nil) {
        
        _refreshTailView = [[EGORefreshTableTailView alloc] initWithFrame:CGRectMake(0.0f, self.myTableView.contentSize.height, 320, self.myTableView.frame.size.height)];
        _refreshTailView.delegate = self;
        [self.myTableView addSubview:_refreshTailView];
        
    }
    
    if (_refreshTailView != nil) {
        float height = MAX(self.myTableView.contentSize.height, self.myTableView.frame.size.height);
        [_refreshTailView setFrame:CGRectMake(0.0f, height, 320, self.myTableView.frame.size.height)];
    }
    
    
}



//顶部刷新事件
- (void)headerRefData
{
        _HeaderReloading = YES;
        pageNo = 1;
        [self loadData];
        
    }

- (void)headerRefDone
{
    _HeaderReloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.myTableView];
}

//底部刷新事件
- (void)bottomRefData
{
    
    
        _TailReloading = YES;
    
    pageNo = microBlogArray.count/20 +1;
    
    [self loadData];
       
}

- (void)bottomRefDone
{
    _TailReloading = NO;
    if (_refreshTailView != nil) {
        
        [_refreshTailView egoRefreshScrollViewDataSourceDidFinishedLoading:self.myTableView];
    }
    
}



#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    
    [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
    //上拉
    if (_refreshTailView != nil) {
        
        [_refreshTailView egoRefreshScrollViewDidScroll:scrollView];
    }
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
    
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    //上拉
    if (_refreshTailView != nil) {
        
        [_refreshTailView egoRefreshScrollViewDidEndDragging:scrollView];
    }
    
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
}


#pragma mark -
#pragma mark EGORefreshTableTailDelegate Methods

- (void)egoRefreshTableTailDidTriggerRefresh:(EGORefreshTableTailView*)view{
	
	[self bottomRefData];
    
}

- (BOOL)egoRefreshTableTailDataSourceIsLoading:(EGORefreshTableTailView*)view{
	
    
    return _TailReloading;
	
}

- (NSDate*)egoRefreshTableTailDataSourceLastUpdated:(EGORefreshTableTailView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view{
    
	[self headerRefData];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view{
	
	//return _reloading; // should return if data source model is reloading
    return _HeaderReloading;
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}



@end
